<template>
  <view class="page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 主要天气信息 -->
    <view class="weather-main">
		
      <!-- 位置信息 -->
      <view class="location-info" @click="chooseLocation">
        <uni-icons type="location" size="16" color="#4CAF50"></uni-icons>
        <text class="location-text">{{ currentLocation }}</text>
        <uni-icons type="right" size="12" color="#999"></uni-icons>
      </view>
      
      <!-- 当前温度 -->
      <view class="current-weather">
        <text class="temperature">{{ weatherDetails.temperature }}°C</text>
        <view class="weather-desc">
          <text class="weather-type">{{ currentWeather.type }}</text>
          <text class="temp-range">最高{{ currentWeather.high }}° 最低{{ currentWeather.low }}°</text>
        </view>
      </view>
	  
    </view>
    
    <!-- 功能卡片区域 -->
    <view class="weather-cards">
      
      <!-- 七日预报 -->
      <view class="weather-card" @click="showSevenDayForecast">
        <view class="card-header">
          <text class="card-title">七日预报</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
        <view class="forecast-preview">
          <view class="forecast-item" v-for="(day, index) in weeklyForecast.slice(0, 3)" :key="index">
            <text class="forecast-day">{{ day.day }}</text>
            <view class="forecast-weather">
              <uni-icons :type="getWeatherIcon(day.type)" size="20" :color="getWeatherColor(day.type)"></uni-icons>
              <text class="forecast-type">{{ day.type }}</text>
            </view>
            <view class="forecast-temp">
              <text class="temp-low">{{ day.low }}°</text>
              <view class="temp-bar">
                <view class="temp-range-bar" :style="getTempBarStyle(day)"></view>
              </view>
              <text class="temp-high">{{ day.high }}°</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 详细信息 -->
    <view class="weather-details">
      <view class="detail-grid">
        <view class="detail-item">
          <!-- <uni-icons type="eye" size="24" color="#4CAF50"></uni-icons> -->
          <text class="detail-label">温度</text>
          <text class="detail-value">{{ weatherDetails.temperature }}°C</text>
        </view>
        <view class="detail-item">
          <!-- <uni-icons type="water" size="24" color="#2196F3"></uni-icons> -->
          <text class="detail-label">湿度</text>
          <text class="detail-value">{{ weatherDetails.humidity }}%</text>
        </view>
        <view class="detail-item">
          <!-- <uni-icons type="navigate" size="24" color="#FF9800"></uni-icons> -->
          <text class="detail-label">体感温度</text>
          <text class="detail-value">{{ weatherDetails.feelst }}°C</text>
        </view>
        <view class="detail-item">
          <!-- <uni-icons type="thermometer" size="24" color="#F44336"></uni-icons> -->
          <text class="detail-label">气压</text>
          <text class="detail-value">{{ weatherDetails.pressure }}hPa</text>
        </view>
        <view class="detail-item">
          <!-- <uni-icons type="sunny" size="24" color="#FFC107"></uni-icons> -->
          <text class="detail-label">风向</text>
          <text class="detail-value">{{ weatherDetails.windDirection }}</text>
        </view>
        <view class="detail-item">
          <!-- <uni-icons type="cloud" size="24" color="#9E9E9E"></uni-icons> -->
          <text class="detail-label">风速</text>
          <text class="detail-value">{{ weatherDetails.windSpeed }}km/h</text>
        </view>
      </view>
    </view>
    
    <!-- 七日预报弹窗 -->
    <uni-popup ref="forecastPopup" type="bottom" :safe-area="false">
      <view class="forecast-container">
        <view class="popup-header">
          <text class="popup-title">七日天气预报</text>
          <view class="popup-close" @click="closeSevenDayForecast">
            <uni-icons type="closeempty" size="20" color="#999"></uni-icons>
          </view>
        </view>
        
        <view class="forecast-list">
          <view class="forecast-day-item" v-for="(day, index) in weeklyForecast" :key="index">
            <view class="day-info">
              <text class="day-name">{{ day.day }}</text>
              <text class="day-date">{{ day.date }}</text>
            </view>
            <view class="weather-info">
              <uni-icons :type="getWeatherIcon(day.type)" size="28" :color="getWeatherColor(day.type)"></uni-icons>
              <text class="weather-type">{{ day.type }}</text>
            </view>
            <view class="temp-info">
              <text class="temp-low">{{ day.low }}°</text>
              <view class="temp-bar-full">
                <view class="temp-range-full" :style="getTempBarStyle(day)"></view>
              </view>
              <text class="temp-high">{{ day.high }}°</text>
            </view>
            <view class="agriculture-advice">
              <text class="advice-text">{{ getAgricultureAdvice(day) }}</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';


uni.setNavigationBarTitle({
	  title:'天气'
})

// 系统信息
const statusBarHeight = ref(0);

// 当前位置
const currentLocation = ref('湖南省 长沙市 芙蓉区');

// 当前天气
const currentWeather = ref({
  temperature: '--',
  type: '--',
  high: '--',
  low: '--'
});

// 七日预报
const weeklyForecast = ref([
  { day: '今天', date: '--', type: '--', high: '--', low: '--' },
  { day: '明天', date: '--', type: '--', high: '--', low: '--' },
  { day: '周六', date: '--', type: '--', high: '--', low: '--' },
  { day: '周日', date: '--', type: '--', high: '--', low: '--' },
  { day: '周一', date: '--', type: '--', high: '--', low: '--' },
  { day: '周二', date: '--', type: '--', high: '--', low: '--' },
  { day: '周三', date: '--', type: '--', high: '--', low: '--' }
]);

// 天气详情
const weatherDetails = ref({
  temperature: '--',
  humidity: '--',
  feelst: '--',
  pressure: '--',
  windDirection: '--',
  windSpeed: '--'
});

// 弹窗引用
const precipitationPopup = ref(null);
const forecastPopup = ref(null);

// 页面初始化
onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;
  
  // 获取未来天气
  getFutureWeather();
  
  //获取实时天气
  getCurrentWeather();
  
  //获取位置信息
  getCurrentLocation();
});

// 获取未来七日天气
const getFutureWeather = () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      let longitude = res.longitude;
      let latitude = res.latitude;
      let url = `https://p74ky2uvdp.re.qweatherapi.com/v7/weather/7d?location=${longitude},${latitude}`;
      
      uni.request({
        url: url,
        method: "GET",
        header: {
          "X-QW-Api-Key": "c7b47495de184e95b64dfababe620ecd"
        },
        success: (response) => {
          if (response.statusCode === 200 && response.data && response.data.daily) {
            let daily = response.data.daily;
            console.log(daily);
            
            // 获取今日日期字符串 (YYYY-MM-DD)
            const today = new Date();
            const todayStr = today.toISOString().split('T')[0];
            
            // 获取明天日期字符串
            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);
            const tomorrowStr = tomorrow.toISOString().split('T')[0];
            
            // 获取后天日期字符串
            const dayAfterTomorrow = new Date(today);
            dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
            const dayAfterTomorrowStr = dayAfterTomorrow.toISOString().split('T')[0];
            
            // 格式化日期函数 (MM-DD)
            function formatDate(fxDate) {
              const parts = fxDate.split('-');
              return `${parts[1]}-${parts[2]}`;
            }
            
            // 获取星期几函数
            function getDayOfWeek(dateStr) {
              const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
              const date = new Date(dateStr + 'T00:00:00'); // 添加时间部分避免时区问题
              return days[date.getDay()];
            }
            
            // 设置当前日期天气
            currentWeather.value = {
              temperature: daily[0].tempMax || '--',
              type: daily[0].textDay,
              high: daily[0].tempMax,
              low: daily[0].tempMin
            };
            
            // 处理七日预报
            weeklyForecast.value = daily.slice(0, 7).map((day) => {
              const dateStr = day.fxDate;
              
              // 根据日期字符串判断显示文本
              let displayDay;
              if (dateStr === todayStr) displayDay = '今天';
              else if (dateStr === tomorrowStr) displayDay = '明天';
              else if (dateStr === dayAfterTomorrowStr) displayDay = '后天';
              else displayDay = getDayOfWeek(dateStr);
              
              return {
                day: displayDay,
                date: formatDate(dateStr),
                type: day.textDay,
                high: day.tempMax,
                low: day.tempMin
              };
            });
          }
        },
        fail: (err) => {
          console.error('未来天气信息获取失败', err);
          //uni.showToast({ title: '获取天气失败', icon: 'none' });
        }
      });
    },
    fail: (err) => {
      console.error('未来天气请求失败', err);
      //uni.showToast({ title: '获取位置失败', icon: 'none' });
    }
  });
};

// 获取位置信息
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
	  let longitude=res.longitude;
	  let latitude=res.latitude;
	  let ulrs=`https://restapi.amap.com/v3/geocode/regeo?output=xml&location=${longitude},${latitude}&key=63334b51a858407e63b9f58290ad01b4`
	  //let ulrs=`https://restapi.amap.com/v3/geocode/regeo?output=xml&location=116.481488,39.990464&key=63334b51a858407e63b9f58290ad01b4`
	  uni.request({
		  url:ulrs,
		  method:"get",
		  success:(response)=>{
			  const parser = new DOMParser();
			  const xmlDoc = parser.parseFromString(response.data, "application/xml");
	  
			  const province = xmlDoc.getElementsByTagName("province")[0].textContent;
			  const city = xmlDoc.getElementsByTagName("city")[0].textContent;
			  const district = xmlDoc.getElementsByTagName("district")[0].textContent;
			  
			  console.log(province);
			  console.log(city);
			  console.log(district);
	  
			  // 拼接地址并赋值给currentLocation
			  currentLocation.value = `${province}  ${city}  ${district}`;
			  
		  },
		  fail: (err) => {
			   console.log(err);
		    uni.showToast({
		      title: '位置信息获取失败',
		      icon: 'none'
		    });
		  }
	  })
    },
    fail: () => {
      uni.showToast({
        title: '位置请求失败',
        icon: 'none'
      });
    }
  });
};

// 获取实时天气
const getCurrentWeather = () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      let longitude = res.longitude;
      let latitude = res.latitude;
      let url = `https://p74ky2uvdp.re.qweatherapi.com/v7/weather/now?location=${longitude},${latitude}`;
      
      uni.request({
        url: url,
        method: "GET",
        header: {
          "X-QW-Api-Key": "c7b47495de184e95b64dfababe620ecd"
        },
        success: (response) => {
          // 关键修改：正确访问响应数据结构
          if (response.statusCode === 200 && response.data && response.data.code === "200") {
            const weatherData = response.data.now;
			
			console.log(response.data.now.obsTime);
			
            weatherDetails.value = {
              temperature: Math.ceil(weatherData.temp),
              humidity: weatherData.humidity,
              feelst: weatherData.feelsLike,
              pressure: weatherData.pressure,
              windDirection: weatherData.windDir,
              windSpeed: weatherData.windSpeed,
              weatherText: weatherData.text,      // 新增：天气状况文本
              observationTime: weatherData.obsTime // 新增：观测时间
            };
			
			
          } 
        },
        fail: (err) => {
          console.error('实时天气信息获取失败', err);
          //uni.showToast({ title: '获取天气失败', icon: 'none' });
        }
      });
    },
    fail: (err) => {
      console.error('实时天气请求失败', err);
      //uni.showToast({ title: '获取位置失败', icon: 'none' });
    }
  });
};

// 获取天气图标
const getWeatherIcon = (type) => {
  const iconMap = {
    '晴': 'sunny',
    '多云': 'cloud',
    '阴': 'cloudy',
    '小雨': 'rain',
    '中雨': 'rain',
    '大雨': 'rain'
  };
  return iconMap[type] || 'cloud';
};

// 获取天气颜色
const getWeatherColor = (type) => {
  const colorMap = {
    '晴': '#FFC107',
    '多云': '#9E9E9E',
    '阴': '#607D8B',
    '小雨': '#2196F3',
    '中雨': '#1976D2',
    '大雨': '#0D47A1'
  };
  return colorMap[type] || '#9E9E9E';
};

// 获取温度条样式
const getTempBarStyle = (day) => {
  // 如果数据为占位符，返回默认样式
  if (day.low === '--' || day.high === '--') {
    return {
      left: '0%',
      width: '0%',
      background: '#e0e0e0'
    };
  }

  const minTemp = 10;
  const maxTemp = 35;
  const lowPercent = ((day.low - minTemp) / (maxTemp - minTemp)) * 100;
  const highPercent = ((day.high - minTemp) / (maxTemp - minTemp)) * 100;

  return {
    left: lowPercent + '%',
    width: (highPercent - lowPercent) + '%',
    background: getWeatherColor(day.type)
  };
};

// 获取农业建议
const getAgricultureAdvice = (day) => {
  // 如果数据为占位符，返回默认提示
  if (day.type === '--') {
    return '数据加载中...';
  }

  if (day.type.includes('雨')) {
    return '适宜室内作业，注意排水';
  } else if (day.type === '晴') {
    return '适宜播种、施肥、收获';
  } else if (day.type === '多云') {
    return '适宜移栽、修剪';
  } else {
    return '注意保温保湿';
  }
};

// 显示降水图
const showPrecipitationChart = () => {
  precipitationPopup.value.open();
};

// 关闭降水图
const closePrecipitationChart = () => {
  precipitationPopup.value.close();
};

// 显示七日预报
const showSevenDayForecast = () => {
  forecastPopup.value.open();
};

// 关闭七日预报
const closeSevenDayForecast = () => {
  forecastPopup.value.close();
};
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd 0%, #e8f5e9 50%, #f1f8e9 100%);
}

.status-bar {
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
}

.weather-main {
  padding: 40rpx 30rpx;
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
  color: #ffffff;
}

.location-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 40rpx;
}

.location-text {
  font-size: 28rpx;
  color: #ffffff;
  flex: 1;
}

.current-weather {
  display: flex;
  align-items: flex-end;
  gap: 30rpx;
  margin-bottom: 40rpx;
}

.temperature {
  font-size: 120rpx;
  font-weight: 400;
  line-height: 1;
  margin-left: 20px;
  margin-bottom: 5px;
}

.weather-desc {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  padding-bottom: 20rpx;
  margin-left: 30px;
}

.weather-type {
  font-size: 24rpx;
  font-weight: 500;
}

.temp-range {
  font-size: 1rem;
  opacity: 0.8;
}

.agriculture-index {
  display: flex;
  justify-content: space-between;
  background-color: rgba(255, 255, 255, 0.15);
  border-radius: 16rpx;
  padding: 24rpx;
}

.index-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  flex: 1;
}

.index-label {
  font-size: 22rpx;
  opacity: 0.8;
}

.index-value {
  font-size: 24rpx;
  font-weight: 600;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  background-color: rgba(255, 255, 255, 0.2);
}

.index-value.index-good {
  background-color: rgba(76, 175, 80, 0.3);
}

.index-value.index-normal {
  background-color: rgba(255, 152, 0, 0.3);
}

.index-value.index-poor {
  background-color: rgba(244, 67, 54, 0.3);
}

.weather-cards {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.weather-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.card-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
}

.precipitation-preview {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.rain-forecast {
  font-size: 28rpx;
  color: #666666;
}

.rain-chart-mini {
  display: flex;
  align-items: flex-end;
  gap: 4rpx;
  height: 60rpx;
}

.rain-bar {
  width: 8rpx;
  background: linear-gradient(to top, #2196F3, #64B5F6);
  border-radius: 4rpx;
  min-height: 4rpx;
}

.forecast-preview {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.forecast-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.forecast-day {
  font-size: 26rpx;
  color: #666666;
  width: 80rpx;
}

.forecast-weather {
  display: flex;
  align-items: center;
  gap: 8rpx;
  width: 120rpx;
}

.forecast-type {
  font-size: 24rpx;
  color: #666666;
}

.forecast-temp {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex: 1;
}

.temp-low, .temp-high {
  font-size: 24rpx;
  color: #666666;
  width: 60rpx;
  text-align: center;
}

.temp-bar {
  flex: 1;
  height: 6rpx;
  background-color: #e0e0e0;
  border-radius: 3rpx;
  position: relative;
}

.temp-range-bar {
  position: absolute;
  height: 100%;
  border-radius: 3rpx;
}

.weather-details {
  padding: 20rpx;
  margin-bottom: 120rpx;
}

.detail-grid {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
}

.detail-label {
  font-size: 24rpx;
  color: #666666;
}

.detail-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 600;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-top: 1rpx solid #e0e0e0;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 100%;
}

.nav-text {
  font-size: 20rpx;
  color: #666666;
  margin-top: 8rpx;
}

.nav-text.active {
  color: #4CAF50;
  font-weight: 600;
}

.precipitation-container, .forecast-container {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  overflow: hidden;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.popup-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
}

.popup-close {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rain-forecast-detail {
  padding: 30rpx;
  text-align: center;
}

.forecast-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
}

.copy-success {
  margin-top: 20rpx;
  padding: 12rpx 24rpx;
  background-color: #4CAF50;
  border-radius: 20rpx;
  display: inline-block;
}

.copy-text {
  font-size: 24rpx;
  color: #ffffff;
}

.rain-chart-container {
  padding: 30rpx;
}

.chart-labels {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.label-item {
  font-size: 24rpx;
  color: #666666;
  text-align: right;
  padding-right: 20rpx;
}

.rain-chart {
  display: flex;
  align-items: flex-end;
  gap: 8rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.rain-column {
  flex: 1;
  background: linear-gradient(to top, #2196F3, #64B5F6);
  border-radius: 4rpx;
  min-height: 8rpx;
}

.time-labels {
  display: flex;
  justify-content: space-between;
}

.time-label {
  font-size: 22rpx;
  color: #999999;
}

.chart-actions {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  border-top: 1rpx solid #e0e0e0;
}

.chart-btn {
  flex: 1;
  height: 80rpx;
  border: 2rpx solid #4CAF50;
  border-radius: 40rpx;
  background-color: transparent;
  color: #4CAF50;
  font-size: 28rpx;
  font-weight: 600;
}

.chart-btn.primary {
  background-color: #4CAF50;
  color: #ffffff;
}

.forecast-list {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.forecast-day-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.forecast-day-item:last-child {
  border-bottom: none;
}

.day-info {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
  width: 100rpx;
}

.day-name {
  font-size: 26rpx;
  color: #333333;
  font-weight: 600;
}

.day-date {
  font-size: 22rpx;
  color: #999999;
}

.weather-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  width: 120rpx;
}

.weather-type {
  font-size: 1rem;
  color: #666666;
}

.temp-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex: 1;
}

.temp-bar-full {
  flex: 1;
  height: 8rpx;
  background-color: #e0e0e0;
  border-radius: 4rpx;
  position: relative;
}

.temp-range-full {
  position: absolute;
  height: 100%;
  border-radius: 4rpx;
}

.agriculture-advice {
  width: 200rpx;
}

.advice-text {
  font-size: 22rpx;
  color: #4CAF50;
  text-align: right;
}
</style>